package cn.jwcat.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Objects;

/**
 * Description: md5加密解密
 */
@Component
public class MD5 {

	public static String md5(String dateString) throws Exception {
		byte[] digest = MessageDigest.getInstance("md5").digest(dateString.getBytes(StandardCharsets.UTF_8));
		StringBuilder md5code = new StringBuilder(new BigInteger(1, digest).toString(16));
		// 如果生成数字未满32位，需要前面补0
		for (int i = 0; i < 32 - md5code.length(); i++) {
			md5code.insert(0, "0");
		}
		return md5code.toString();
	}

	public static String md5PlusSalt(String keyword) {
		//md5加密
		String md5 = DigestUtils.md5Hex(keyword);
		//md5+盐
		return getString(md5);
	}

	// 解密+盐
	public static String md5MinusSalt(String md5) {
		return getString(md5);
	}

	private static String getString(String md5) {
		char[] cArray = md5.toCharArray();
		for (int i = 0; i < cArray.length; i++) {
			if (cArray[i] >= 48 && cArray[i] <= 57) {
				cArray[i] = (char) (105 - cArray[i]);
			}
		}
		return String.valueOf(cArray);
	}

	public static boolean getTrue(String password, String dataBasePassword) {
		return Objects.equals(password, md5MinusSalt(dataBasePassword));
	}

	public static void main(String[] args) throws Exception {
		String password = "e10adc3949ba59abbe56e057f20f883e";
		String ePassword = "e89adc6050ba40abbe43e942f79f116e";
		String md5 = DigestUtils.md5Hex(password);
		System.out.println("md5加密后：" + "\n" + md5);
		String md5salt = MD5.md5PlusSalt(password);
		System.out.println("加盐后：" + "\n" + md5salt);
		String word = MD5.md5MinusSalt(password);
		System.out.println("解密后：" + "\n" + word);
		// e89adc6050ba40abbe43e942f79f116e
	}
}

